package com.cumt.threeway.view.widget;

import android.content.Context;
import android.graphics.Color;
import android.os.Handler;
import android.support.annotation.ColorRes;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.OnScrollListener;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cumt.threeway.R;
import com.cumt.threeway.model.Item;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


/**
 * Created by Chuan.Shen on 2015/11/30.
 */
public class ShelfTabView extends LinearLayout {
    public static interface ItemClick {
        public void onItemClick(int tagId);
    }

    private final int LEFT = 0;
    private final int RIGHT = 1;

    private final float SCALE_COEFFICIENT = 0.2f;
    private final float SCALE_MIN = 1f;
    private final float SCALE_MAX = SCALE_MIN + SCALE_COEFFICIENT;

    private final int SELECT_COLOR = 0X26dfa0;
    private final int NORMAL_COLOR = 0X8e8e8e;

    private RecyclerView mRecyclerView;
    private ImageView mLeftCaseView;
    private ImageView mRightCaseView;
    private ImageView mRightArrow;

    private LinearLayoutManager mLayoutManager;
    private Adapter mAdapter;
    private ItemClick mItemClick;
    private int marginRight = 0;

    private ArrayList<Item> mItems = new ArrayList<Item>();

    private HashMap<Integer, View> mTitleViews = new HashMap<Integer, View>();

    private int mSelectPosition = 0;

    private Handler mHandler = new Handler();

    public ShelfTabView(Context context) {
        super(context);
        init();
    }

    public ShelfTabView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public ShelfTabView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    private void init() {
        marginRight = getResources().getDimensionPixelSize(R.dimen.cumt_threeway_15);
        View view = LayoutInflater.from(getContext()).inflate(R.layout.shelf_tab_view, null);
        addView(view);
        mRecyclerView = (RecyclerView) findViewById(R.id.shelf_tab_recyclerview);
        mLeftCaseView = (ImageView) findViewById(R.id.bookcase_left);
        mRightCaseView = (ImageView) findViewById(R.id.bookcase_right);
        mRightArrow = (ImageView)findViewById(R.id.iv_right_arrow);
        mRightArrow.setOnClickListener( new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mSelectPosition < mItems.size() - 1) {
                    changeSelect(mSelectPosition + 1);
                }else {
                    mRecyclerView.smoothScrollToPosition(mItems.size());
                }
            }
        });
        mAdapter = new Adapter();
        mLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setAdapter(mAdapter);
        mRecyclerView.addOnScrollListener(new OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    resetCaseVisible();
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                if (mLayoutManager.findLastCompletelyVisibleItemPosition() == mItems.size() - 1) {
                    setRightArrowVisibility(true);
                    setMarginRight(0);
                } else {
                    setRightArrowVisibility(false);
                    setMarginRight(marginRight);
                }
            }
        });
    }

    private void setMarginRight(int marginRight){
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)mRecyclerView.getLayoutParams();
        params.setMargins(0,0,marginRight,params.bottomMargin);
        mRecyclerView.setLayoutParams(params);
    }

    private void setRightArrowVisibility(boolean gone){
        if(gone){
            mRightArrow.setVisibility(View.GONE);
        }else {
            mRightArrow.setVisibility(View.VISIBLE);
        }
    }
    private void changeSelectPosition(int selectPosition) {
        if (mSelectPosition == selectPosition) {
            return;
        }
        this.mSelectPosition = selectPosition;
        if (mItemClick != null) {
            mHandler.removeCallbacksAndMessages(null);
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mItemClick.onItemClick(getItem(mSelectPosition).getId());
                }
            }, 100);
        }
    }

    private void resetCaseVisible() {
        int firstVisible = mLayoutManager.findFirstVisibleItemPosition();
        int lastVisible = mLayoutManager.findLastVisibleItemPosition();
        if (firstVisible == 0) {
            mLeftCaseView.setVisibility(View.GONE);
        } else {
            mLeftCaseView.setVisibility(View.VISIBLE);
        }

        if (lastVisible == mItems.size() - 1) {
            mRightCaseView.setVisibility(GONE);
        } else {
            mRightCaseView.setVisibility(VISIBLE);
        }
    }


    public Item getItem(int position) {
        return mItems.get(position);
    }

    public void changeSelect(int position) {
        changeSelectPosition(position);
        postDelayed(new Runnable() {
            @Override
            public void run() {
//                getLayoutManager().smoothScrollToPosition(ShelfTabView.this, null, position);
                updataUI();
                int firstVisible = mLayoutManager.findFirstVisibleItemPosition();
                int lastVisible = mLayoutManager.findLastVisibleItemPosition();
                if (lastVisible - 1 <= mSelectPosition) {
                    mRecyclerView.smoothScrollToPosition(mSelectPosition + 1);
                } else if (firstVisible + 1 >= mSelectPosition) {
                    if (firstVisible > 0) {
                        firstVisible -= 1;
                    }
                    mRecyclerView.smoothScrollToPosition(firstVisible);
                }
            }
        }, 100);
    }

    public void updataUI() {
        mAdapter.notifyDataSetChanged();
        resetCaseVisible();
    }

    public void setItemClickListener(ItemClick itemClick) {
        mItemClick = itemClick;
    }

    private void scaleView(View view, float scale) {
        view.setScaleX(scale);
        view.setScaleY(scale);
    }

    private void modifyTitleColor(TextView textView, @ColorRes int color) {
        textView.setTextColor(getResources().getColor(color));
    }

    private boolean offset = true;
    private int direction = RIGHT; // 0: 左滑 1：右滑
    public void onPageScrolled(int position, float positionOffset) {
        if (positionOffset == 0f) {
            offset = true;
            return;
        }

        if (offset) {
            offset = false;
            if (position == mSelectPosition) {
                direction = RIGHT;
            } else {
                direction = LEFT;
            }
        }
        View nextView = null;
        View view = null;
        float scale = 0f;
        float offset = 0;
        switch (direction) {
            case LEFT: // 向左滑动
                if (mSelectPosition > 0) {
                    nextView = mTitleViews.get(position);
                    view = mTitleViews.get(position + 1);
                    offset = 1 - positionOffset;
                    scale = (1 - positionOffset) * SCALE_COEFFICIENT;
                }
                break;
            case RIGHT: // 向右滑动
                if (position < mItems.size() - 1) {
                    nextView = mTitleViews.get(position + 1);
                    view = mTitleViews.get(position);
                    offset = positionOffset;
                    scale = positionOffset * SCALE_COEFFICIENT;
                }
                break;
        }

        if (nextView == null || view == null) {
            return;
        }

        scaleView(nextView, SCALE_MIN + scale);
        scaleView(view, SCALE_MAX - scale);

        int diffColor = getColor(offset);
        ((TextView) nextView).setTextColor(Color.parseColor(String.format("#%06x", (NORMAL_COLOR - diffColor))));
        ((TextView)view).setTextColor(Color.parseColor(String.format("#%06x", (SELECT_COLOR + diffColor))));
    }

    private int getColor(float scale) {
        int red = ((NORMAL_COLOR & 0xFF0000) >> 16) - ((SELECT_COLOR & 0xFF0000) >> 16);
        int greed = ((NORMAL_COLOR & 0xFF00) >> 8) - ((SELECT_COLOR & 0xFF00) >> 8);
        int blue = (NORMAL_COLOR & 0xFF) - (SELECT_COLOR & 0xFF);

        return ((int)(red * scale) << 16) + ((int)(greed * scale) << 8) + ((int)(blue * scale));
    }

    public void setItems(ArrayList<Item> items) {
        mItems = items;
    }

    public int getPositionByTagId(int tagId) {
        for (int index = 0; index < mItems.size(); index++) {
            Item item = mItems.get(index);
            if (item.getId() == tagId) {
                return index;
            }
        }
        return 0;
    }

    private class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> implements OnClickListener {

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.shelf_tab_item, parent, false);
            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
            Item item = mItems.get(position);
            holder.mTitleView.setText(item.getName());
            if (mSelectPosition == position) {
                scaleView(holder.mTitleView, SCALE_MAX);
                modifyTitleColor(holder.mTitleView, R.color.bookshelf_case_typeface_select);
            } else {
                scaleView(holder.mTitleView, SCALE_MIN);
                modifyTitleColor(holder.mTitleView, R.color.bookshelf_case_typeface_nor);
            }
            holder.mTitleView.setTag(position);
            Iterator<Map.Entry<Integer, View>> iter = mTitleViews.entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry<Integer, View> entry = iter.next();
                View view = entry.getValue();
                if (view == holder.mTitleView) {
                    iter.remove();
                    break;
                }
            }
            mTitleViews.put(position, holder.mTitleView);
        }

        @Override
        public int getItemCount() {
            return mItems.size();
        }

        @Override
        public void onClick(View view) {
            int position = (Integer) view.getTag();
            Item item = mItems.get(position);
            mItemClick.onItemClick(item.getId());
        }

        public class ViewHolder extends RecyclerView.ViewHolder {
            public TextView mTitleView;
            public ViewHolder(View itemView) {
                super(itemView);
                mTitleView = (TextView) itemView.findViewById(R.id.titleView);
                mTitleView.setOnClickListener(Adapter.this);
            }
        }
    }
}
